package homework.gademo.web;

import homework.gademo.common.SessionUtil;
import homework.gademo.domain.UserInfo;
import homework.gademo.service.UserService;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping
public class UserController {
	@Resource
	UserService userService;
	
	
    @RequestMapping("/")
    public String index(){
    	if (SessionUtil.getUserId() != null ) {
    		return "redirect:/hello";
		}else {
			return "index";
		}
         //当浏览器输入/index时，会返回 /static/home.html的页面
    }
    
    @RequestMapping("/register")
    public String register(Model model) {
    	model.addAttribute("gakey",userService.getGoogleKey());
        return  "register";
    }
	
    @RequestMapping("/hello")
    public String hello(Model model) {
    	model.addAttribute("user",SessionUtil.getUserId());
        return  "hello";
    }
    
	@RequestMapping("/user/login")
	public String login(@ModelAttribute  UserInfo userInfo,Long gaCode) {
		if (userService.login(userInfo,gaCode)) {
			return "redirect:/hello";
		}
		else {
			return "redirect:/";
		}
		
		
	}
	
	@RequestMapping("/user/logout")
	public String logout() {
		SessionUtil.getSession().invalidate();
		return "redirect:/";
	}
	
	
	@RequestMapping("/user/register")
	public String registor(@ModelAttribute  UserInfo userInfo) {
		if (userService.register(userInfo)) {
			
			return "redirect:/";
		}
		else {
			return "redirect:/register";
		}
		
		
	}
}
